<template>
  <el-main class="match-index" :style="{ overflow: 'auto' }">
    <div class="container-xl">
      <div class="row">
        <div class="col ro imgaa">
          <el-button class="matchlink" @click="$router.push(`/activity/${match.ID}`)">返回比赛主页</el-button>

          <h3 v-if="!show">自动评卷中，已经完成{{ key }}/{{ question.length }}……</h3>
          <h3 v-else v-text="match.name"></h3>
          <div class="fen" v-if="match.result != 3">
            <h1>{{ show ? df : '???' }}</h1>
            <span>分</span>
          </div>
        </div>
      </div>
      <div class="row" v-if="match.result != 3">
        <div class="col bg-white m-p-6">
          <el-table :data="show ? data : []" border style="width: 100%">
            <el-table-column type="index" width="80" label="题号"></el-table-column>
            <el-table-column prop="matchquestion.name" width="350" label="题目名称"></el-table-column>
            <el-table-column prop="matchquestion.type" label="类型" width="80"></el-table-column>
            <el-table-column width="100" label="提交答案">
              <template #default="scope">
                <span class="cu" v-if="scope.row.matchquestion.type === '代码'" text @click="down(scope.row)">下载源码
                </span>
                <span v-else>{{ unfanu(scope.row.info.answer) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="df" width="80" label="得分"></el-table-column>
            <el-table-column prop="result" label="编程题测试点">
              <template #default="scope">
                <div v-if="
                  scope.row.type === '代码' &&
                  Array.isArray(scope.row.resultdataarr)
                ">
                  [
                  <span v-for="(v, key) in scope.row.resultdataarr" :key="'a_' + key">
                    <span :class="ALLTYPE[v][1]">
                      {{ ALLTYPE[v][0] }}
                      {{ key !== scope.row.resultdataarr.length - 1 ? "," : "" }}
                    </span>
                  </span>
                  ]
                </div>
                <div v-else>
                  {{ scope.row.resultdata }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="row" v-else>
        <div class="col bg-white m-p-6">
          <h5>您已成功提交本次试卷！</h5>
          <h5>等待工作人员确认后将统一公布比赛结果，预祝您取得不错的成绩！</h5>
        </div>
      </div>
    </div>
  </el-main>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import {
  computed,
  onMounted,
  ref,
  toRefs,
  watch,
} from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  asyncfindcountmatchquestion,
  asyncselectmatchuserquestion,
} from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { ALLTYPE } from "@/util/jianchatime";
const p = withDefaults(defineProps<{ time: any, match: Studycodemodel.Iactivity, statematch: "开始" | "结束" }>(), {
  statematch: '开始'
})

const { match, statematch } = toRefs(p);
const data = computed(() => {
  return matchuserquestion.value.map(e => {
    const _matchuserquestion = question.value.find(t => t.ID === e.questionid)
    return {
      ...e,
      matchquestion: _matchuserquestion
    }
  })
});
onMounted(() => {
  store.state.socket.on('key', (e) => {
    key.value = e
    if (e === question.value.length) {
      start()
    }
  })
  start();
});
const num = ref(Infinity);
const show = computed(() => {
  if (match.value.result === 3) {
    return true;
  }
  return data.value.length == num.value;
});
const store = useStore(Storekey);
const router = useRouter();
const user = computed(() => {
  return store.state.user;
});

const matchuserquestion = ref<(Studycodemodel.Imatchuserquestion)[]>([])
const question = ref<Studycodemodel.Iquestion[]>([])
const activity = ref<Studycodemodel.Iactivity>()
const key = ref(0)
const df = computed(() => {
  let d = 0;
  data.value.forEach((v) => {
    console.log(v.df)
    d = d + (v.df || 0);
  });
  return d;
});

watch(
  () => statematch.value,
  (d) => {
    if (d === "结束") {
      start();
    } else if (d === "开始") {
      ElMessage.info("开始判题");
    }
  }
);

function unfanu(t?: null | boolean | string | undefined) {
  if (t === undefined) {
    return ''
  } else if (t === null) {
    return ''
  } else if (t === true) {
    return '正确'
  } else if (t === false) {
    return '错误'
  } else if (Array.isArray(t)) {
    return t.toString()
  } else {
    return t
  }
}

async function start() {
  if (!user.value) {
    ElMessage.error("请登录");
    router.push("/");
    return;
  }
  try {
    const id = match.value.matchquestionbank?.[0].ID;
    if (id) {
      num.value = await asyncfindcountmatchquestion({ questionbankid: id });
    }
    const data = await asyncselectmatchuserquestion({
      ID: match.value.ID || 0,
      my: true,
    });

    matchuserquestion.value = data.userquestion
    question.value = data.question
  } catch (e: any) {
    ElMessage.info(e);
  }
}

const index = ref(0);


function down(row: Studycodemodel.Imatchuserquestion) {
  const { context, language } = row;
  if (context) {
    let t = ".cpp";
    if ("c" === language) {
      t = ".c";
    }
    if ("python" === language) {
      t = ".py";
    }
    const bo = new File(
      [context],
      user.value?.name + "_" + row.matchquestion?.name + t,
      {
        type: "text/plain",
      }
    );
    var a = document.createElement("a");
    a.download = user.value?.name + "_" + row.matchquestion?.name + t;
    a.href = URL.createObjectURL(bo);
    a.click();
  } else {
    ElMessage.error("代码为空");
  }
}
</script>

<style scoped>
.match-index {
  background-image: url(https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/bc_jinrubishai.png);
  background-size: cover;
  background-position: center;
  background-repeat: repeat;
  padding-top: 96px;
  min-height: 100vh;
}

.imgaa {
  height: 320px;
  background-image: url(https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/oj_bisaijiesuanbanner.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  padding: 48px;
  position: relative;
}

.imgaa h3 {
  font-size: 36px;
  color: var(--color-1f);
}

.container-xl .ro {
  box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.25);
  border-radius: 12px 12px 0px 0px;
}

h3 {
  color: #1a1a1a;
  font-size: 32px;
  font-weight: bold;
}

.fen {
  margin-bottom: 10px;
  min-width: 330px;
  height: 158px;
  position: absolute;
  left: -25px;
  top: 138px;
  background-color: #fff;
  z-index: inherit;
  padding-left: 73px;
  padding-right: 73px;
  padding-top: 24px;
  color: var(--color-cheng);
  box-shadow: 4px 4px 8px 4px rgba(0, 0, 0, 0.08);
  border-radius: 0px 24px 24px 0px;
}

.fen h1 {
  font-weight: bold;
  font-size: 96px;
  display: inline-block;
}

.fen span {
  font-size: 36px;
}

.matchlink {
  position: absolute;
  top: 24px;
  right: 24px;
}
</style>